package com.zzwtel.autocode.beetl;

import java.util.ArrayList;
import java.util.List;

import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.resource.FileResourceLoader;

import com.zzwtel.autocode.template.constants.TemplatePath;
import com.zzwtel.autocode.template.model.Property;
import com.zzwtel.autocode.template.model.Table;
import com.zzwtel.autocode.template.model.UIModel;
import com.zzwtel.autocode.util.FileUtil;
import com.zzwtel.autocode.util.HumpUtil;
import com.zzwtel.autocode.util.PathUtil;
import com.zzwtel.autocode.util.StrKit;

/**
 * 列表js模板生成类
 * @author yangtonggan
 * @date 2016-3-8
 */

public class ListJsTemplate {

	public void generate(UIModel vm, String modularDir) {
		try{			
			String root = PathUtil.getTemplateRoot();
			FileResourceLoader resourceLoader = new FileResourceLoader(root,"utf-8");
			Configuration cfg = Configuration.defaultConfiguration();
			GroupTemplate gt = new GroupTemplate(resourceLoader, cfg);
			//Template t = gt.getTemplate("/html/@{entity_model}_list.html");
			Template t = gt.getTemplate(TemplatePath.LIST_JS_TEMPLATE);	
			String model = vm.getTable().getModel();			
			//首字母小写，驼峰命名
			t.binding("entityModel", model);
			//首字母大写，驼峰命名
			t.binding("EntityModel", StrKit.firstCharToUpperCase(model));
			//全部大写，下划线分割
			String _model = HumpUtil.underscoreName(model);
			t.binding("ENTITY_MODEL", _model);
			//全部小写，下划线分割			
			t.binding("entity_model", HumpUtil.toLowerCase(_model));
			
			List<Property> list = new ArrayList<Property>();
			Property prop = new Property();
			prop.setName("name");
			list.add(prop);
			
			Property prop2 = new Property();
			prop2.setName("area_id");
			list.add(prop2);
			
			t.binding("fields", list);
			String data = t.render();			
			String out = PathUtil.getOutRoot();			
			String fileName = StringTemplate.getFileName(TemplatePath.LIST_JS_TEMPLATE,"entity_model",HumpUtil.toLowerCase(_model));		
			FileUtil.write(out+modularDir+fileName, data);
		}catch(Exception e){
			throw new RuntimeException(e);
		}
	}
	
	public static void main(String[] args){
		ListJsTemplate jft = new ListJsTemplate();
		UIModel m = new UIModel();
		m.setTable(new Table());
		m.getTable().setModel("area");
		jft.generate(m, "system");
	}

}
